package cn.b.sky.user.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;

/**
 * 
 * <strong>Title : ProxyServlet.java<br></strong>
 * <strong>Package : cn.b.sky.user.filter<br></strong>
 * <strong>Description : </strong>代理servlet<br> 
 * <strong>Create on : 2016-7-12 上午10:06:37<br></strong>
 * <p>
 * @author lidapeng<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
public class ProxyServlet implements Servlet {

  private static final Logger log = LoggerFactory.getLogger(ProxyServlet.class);
  
  public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation";

  private final String name;

  private final Servlet servlet;

  private final Map<String, String> map;

  
  private final boolean enable;
  
  public ProxyServlet(String name, Servlet servlet) {
    this(name, servlet, Collections.emptyMap(), true);
  }

  public ProxyServlet(String name, Servlet servlet, Map<String, String> map) {
    this(name, servlet, map, true);
  }

  public ProxyServlet(String name, Servlet servlet, boolean enable) {
    this(name, servlet, Collections.emptyMap(), enable);
  }

  public ProxyServlet(String name, Servlet servlet, Map map, boolean enable) {
    this.name = name;
    this.servlet = servlet;
    this.map = map;
    this.enable = enable;
  }

  @Override
  public void init(ServletConfig config) throws ServletException {
    if (this.enable) {
      ProxyServletConfig proxyServletConfig = new ProxyServletConfig(config.getServletContext());

      proxyServletConfig.setServletName(this.name);
      proxyServletConfig.setMap(this.map);
      this.servlet.init(proxyServletConfig);
    }
  }

  @Override
  public ServletConfig getServletConfig() {
    return this.servlet.getServletConfig();
  }

  @Override
  public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    log.trace("{}", this.name);

    if (this.enable) {
      this.servlet.service(req, res);
    } else {
      log.trace("skip");
      ((HttpServletResponse) res).sendError(404);
    }
  }

  @Override
  public String getServletInfo() {
    return this.name;
  }

  @Override
  public void destroy() {
    if (this.enable) {
      this.servlet.destroy();
    }
  }

  public String getName() {
    return this.name;
  }  
}
